<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElTree, ElTooltip } from 'element-plus'
import type { TreeNode, ContentItem } from '@/models'
import { buildTreeData } from '@/utils/tree_data'

const emit = defineEmits<{
  (e: 'content-click', data: ContentItem): void
}>()

const props = defineProps<{
  data: Array<ContentItem>
}>()

const expandedItems = ref<string[]>([])

const treeData = computed(() => {
  return buildTreeData(props.data)
})

const defaultProps = {
  children: 'children',
  label: 'title',
}

const handleNodeClick = (data: TreeNode) => {
  if (data.children) {
    toggleExpand(data.path)
  } else {
    emit('content-click', data)
  }
}

const toggleExpand = (path: string) => {
  const index = expandedItems.value.indexOf(path)
  if (index === -1) {
    expandedItems.value.push(path)
  } else {
    expandedItems.value.splice(index, 1)
  }
}
</script>

<template>
  <div class="tree-container">
    <el-tree
      :data="treeData"
      :props="defaultProps"
      :expand-on-click-node="false"
      :default-expanded-keys="expandedItems"
      node-key="path"
      @node-click="handleNodeClick"
    >
      <template #default="{ node, data }">
        <div class="custom-tree-node">
          <el-tooltip
            v-if="!data.isDirectory"
            :content="data.path"
            placement="top"
          >
            <span :class="{ 'directory-title': data.isDirectory }">
              {{ node.label }}
            </span>
          </el-tooltip>
          <span v-else :class="{ 'directory-title': data.isDirectory }">
            {{ node.label }}
          </span>
          <div v-if="!data.isDirectory && data.tags" class="node-tags">
            <span v-for="tag in data.tags" :key="tag" class="tag">
              {{ tag }}
            </span>
          </div>
        </div>
      </template>
    </el-tree>
  </div>
</template>

<style scoped>
.tree-container {
  font-family: Arial, sans-serif;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
}

.directory-title {
  color: #1976d2;
  font-weight: bold;
}

.node-tags {
  margin-left: 10px;
}

.tag {
  display: inline-block;
  background-color: #e0f7fa;
  padding: 2px 6px;
  border-radius: 4px;
  margin-right: 4px;
  font-size: 12px;
}
</style>
